import Vue from 'vue'
import Vuex from 'vuex'
import Web3 from 'web3';

Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		navState: 0,
		account: '',
		net: 0,
		test: "有用没用"
	},
	mutations: {
		setNav: function (state, sta) {
			state.navState = sta;
		},
		SETACCOUNTS: (state, account) => {
			state.account = account;
		},
		SETNET: (state, net) => {
			state.net = net;
		},
	},
	actions: {
		async setWallet() {
			var web3Provider;
			if (window.ethereum) {
				web3Provider = window.ethereum;
				try {
					await web3Provider.enable();
				} catch (error) {
					console.error('User denied account access');
				}
			}
		},
		async setWebProvider({ commit }) {
			var web3Provider;
			if (window.ethereum) {
				web3Provider = window.ethereum;
				try {
					await web3Provider.enable();
				} catch (error) {
					// 用户不授权时
					console.error('User denied account access');
				}
				const web3js = new Web3(web3Provider); //web3js就是你需要的web3实例
				web3js.eth.net.getId(function (error, result) {
					if (!error) {
						commit('SETNET', result);
					}
				});
				web3js.eth.getAccounts(function (error, result) {
					if (!error) {
						commit('SETACCOUNTS', result[0]);
					}
				});
				web3Provider.on('networkChanged', function (networkIDstring) {
					commit('SETNET', networkIDstring);
				});
				web3Provider.on('accountsChanged', function (accounts) {
					commit('SETACCOUNTS', accounts[0]);
					console.log('切换账号', accounts);
				});
			}
		},
	},
})
export default store